package com.ccteam.shared.domain.user

import com.ccteam.model.Resource
import com.ccteam.model.user.UserPhoneVerifyDTO
import com.ccteam.network.ApiError
import com.ccteam.network.ApiResult
import com.ccteam.shared.core.UserCore
import com.ccteam.shared.data.user.UserRepository
import com.ccteam.shared.domain.SuspendUseCase
import com.ccteam.shared.domain.user.VerifyPhoneDataUseCase.VerifyPhoneRequest
import kotlinx.coroutines.Dispatchers
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/4/16
 *
 * 修改用户手机号的Domain层
 * 传入[VerifyPhoneRequest] 验证手机号请求包装
 * 返回[Nothing]
 */
class VerifyPhoneDataUseCase @Inject constructor(
    private val userCore: UserCore,
    private val userRepository: UserRepository
): SuspendUseCase<VerifyPhoneRequest, Nothing?>(
    Dispatchers.IO
) {

    override suspend fun execute(parameters: VerifyPhoneRequest): Resource<Nothing?> {
        val userInfo = userCore.userInfo.value
        val isLogin = userCore.isLogin.value

        if(!isLogin || userInfo.userToken.isNullOrEmpty() || userInfo.userId.isNullOrEmpty()){
            return Resource.Error(ApiError.unknownCode,"非法操作")
        }
        // 是否为新手机号
        val result = if(parameters.isNewPhone){
            userRepository.verifyNewPhone(userInfo.userToken, UserPhoneVerifyDTO(
                parameters.phone,parameters.code
            )
            )
        } else {
            userRepository.verifyOldPhone(userInfo.userToken,UserPhoneVerifyDTO(
                parameters.phone,parameters.code
            ))
        }
        return when(result){
            is ApiResult.Success -> {
                Resource.Success(null)
            }
            is ApiResult.Failure -> {
                Resource.Error(result.errorCode,result.errorMsg)
            }
            else -> {
                Resource.Error(ApiError.serverErrorCode,"未知错误")
            }
        }
    }

    /**
     * 验证手机号请求包装
     *
     * @param isNewPhone 是否是验证新手机号，如果为false则代表验证旧手机号
     * @param phone 手机号
     * @param code 验证码
     */
    data class VerifyPhoneRequest(
        val isNewPhone: Boolean,
        val phone: String,
        val code: String
    )
}